package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        try {
            //获取原始文件名
            String originalFilename =imgFile.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf-1);
            //使用UUID随机产生文件名称，防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //图片上传成功
            Result result = new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS);
            result.setData(fileName);
            //将上传图片名称存入Redis，基于Redis的Set集合存储
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            //图片上传失败
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
    //设置添加权限
    @PreAuthorize("hasAnyAuthority('SETMEAL_ADD')")
    @RequestMapping("/add")
    //添加
    public Result add(@RequestBody Setmeal setmeal , Integer[] checkgroupIds){
        try {
            //调用添加方法
            setmealService.add(setmeal,checkgroupIds);
        }catch (Exception e ){
            //返回添加失败
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        //返回添加成功
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }
    //设置权限
    @PreAuthorize("hasAnyAuthority('SETMEAL_QUERY')")
    @RequestMapping("/findPage")
    //分页查询
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
            //调用分页查询方法
            PageResult pageResult = setmealService.pageQuery(
                    queryPageBean.getCurrentPage(),
                    queryPageBean.getPageSize(),
                    queryPageBean.getQueryString()
            );
            //返回分页查询结果
            return pageResult;
    }

    @RequestMapping("/findById")
    //根据id查询数据
    public Result findById(Integer id) {
        //调用查询方法
        Setmeal setmeal = setmealService.findById(id);
        //判断查询结果是否为空
        if (setmeal != null) {
            //新建查询成功的result
            Result result = new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS);
            //将查询结果封装到查询成功的result中
            result.setData(setmeal);
            //返回result
            return result;
        } else {
            //返回查询失败
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    //设置编辑权限
    @PreAuthorize("hasAnyAuthority('SETMEAL_EDIT')")
    @RequestMapping("/edit")
    //编辑
    public Result edit(@RequestBody Setmeal setmeal ,Integer[] checkgroupIds  ){
        //try
        try {
            //根据setmeal获得id 根据id查询数据库对应的setmeal
            Setmeal s = setmealService.findById(setmeal.getId());
            //删除Rides缓存
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,s.getImg());
            //调用编辑方法，传入页面传过来的setmeal和 checkgroupId
            setmealService.edit(setmeal, checkgroupIds);
            //返回编辑成功
            return new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS);
        }catch (Exception e){
            //返回编辑失败
            return  new Result(false,MessageConstant.EDIT_SETMEAL_FAIL);
        }
    }
    @RequestMapping("/findSetmealIdsByGroupId")
    //通过groupId查询setmeal
    public Result findSetmealIdsByGroupId(Integer id){
        //try
        try {
            //根据页面id查询checkgroupId集合
            List<Integer> checkgroupIds = setmealService.findSetmealIdsByGroupId(id);
            //返回查询成功
            return new Result(true,MessageConstant.QUERY_CHECKGROUP_SUCCESS,checkgroupIds);
        }catch (Exception e){
            e.printStackTrace();
            //返回查询失败
            return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
        }
    }
    //设置删除权限
    @PreAuthorize("hasAnyAuthority('SETMEAL_DELETE')")
    @RequestMapping("/delete")
    //删除
    public Result delete(Integer id ){
        //try
        try{
            //根据页面id查询setmeal
            Setmeal s = setmealService.findById(id);
            //删除Rides缓存
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,s.getImg());
            //调用删除方法
            setmealService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            //返回删除失败
            return new Result(false,MessageConstant.DELETE_SETMEAL_FAIL);
        }
        //返回删除成功
        return new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS);
    }
}
